package pers.sen.flux.controller;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.sen.flux.pojo.User;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

@RestController
public class UserController {

    @GetMapping("/user/sync")
    public ResponseEntity<User> getUserSync() {
        long start = System.currentTimeMillis();
        System.out.println("sync 开始执行");

        // 执行业务
        User user = getUser();

        System.out.println("sync 执行完毕 : " + (System.currentTimeMillis() - start));
        return ResponseEntity.ok(user);
    }
    // 模拟业务
    private User getUser(){
        try {
            // 模拟业务耗时3秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return User.of("Rose", 18);
    }


    @GetMapping("/user/async")
    public Mono<User> getUserAsync() {
        long start = System.currentTimeMillis();
        System.out.println("async 开始执行");

        // 执行业务
        Mono<User> userMono = Mono.fromSupplier(this::getUser);

        System.out.println("async 执行完毕 : " + (System.currentTimeMillis() - start));
        return userMono;
    }


    @GetMapping("/user/flux")
    public Flux<User> getUserFlux() {
        long start = System.currentTimeMillis();
        System.out.println("flux 开始执行");

        Flux<User> flux = getUserWithFlux();
        System.out.println("flux 执行完毕 : " + (System.currentTimeMillis() - start));
        return flux;
    }

    private Flux<User> getUserWithFlux() {
        return Flux.interval(Duration.ofSeconds(1))// 每隔1秒发射一个元素
                .take(3) // 取前3个元素
                // 将元素转为一个User对象
                .map(i -> User.of("user_" + i, 20 + i.intValue()));
    }


    @GetMapping(value = "/user/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getUserStream() {
        long start = System.currentTimeMillis();
        System.out.println("flux 开始执行");

        Flux<User> flux = getUserWithFlux();
        System.out.println("flux 执行完毕 : " + (System.currentTimeMillis() - start));
        return flux;
    }



}